package com.what21.netfwd;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer extends Thread {

	private AddressInfo originalAddr;
	private AddressInfo forwardAddr;
	private ServerSocket server;

	public TCPServer(AddressInfo originalAddr, AddressInfo forwardAddr) {
		this.originalAddr = originalAddr;
		this.forwardAddr = forwardAddr;
	}

	public void run() {
		try {
			server = new ServerSocket();
			server.bind(originalAddr.toAddress());
			ForwardUtil.debug("TCP Server listener > " + originalAddr + " start.");
			while (true) {
				try {
					Socket client = server.accept();
					Socket forward = new Socket(forwardAddr.getAddress(), forwardAddr.getPort());
					ClientThread clientThread = new ClientThread(client, forward);
					clientThread.start();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (NullPointerException e) {
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void close() {
		if (this.server != null) {
			try {
				this.server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			this.server = null;
		}
	}

}